package com.java.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.java.model.Mail;

public class MailUtil {
	public static void main(String[] args) throws IOException {
//		TestMail.sendMail();
		Mail mail = new Mail();
		mail.setContext("test...");
		MailUtil.sendMail(AppConfig.smailName, AppConfig.rmailName, AppConfig.smailName, AppConfig.spasswd,mail);
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		List<Mail> rmailList = MailUtil.receiveMail(AppConfig.rmailName, AppConfig.rpasswd);
		System.out.println(rmailList.size());
		// //TestMail.receiveMail();
		// TestMail.deleteMail();
	}

	/**
	 * send mail
	 */
	public static void sendMail(String from, String to, String userName, String pwd, Mail mail) {
		String host = "smtp.163.com";// 邮件服务器
//		String from = "zhezhiyong@163.com";// 发件人地址
//		String to = "wy245120020@163.com";// 接受地址（必须支持pop3协议）
//		String userName = "zhezhiyong@163.com";// 发件人邮件名称
//		String pwd = "";// 发件人邮件密码
		Properties props = new Properties();
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.auth", "true");

		Session session = Session.getDefaultInstance(props);
		session.setDebug(true);

		MimeMessage msg = new MimeMessage(session);
		try {
			msg.setFrom(new InternetAddress(from));
			msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// 发送
			msg.setSubject("进度通知邮件");// 邮件主题
			msg.setText(mail.getContext());// 邮件内容
			msg.saveChanges();

			Transport transport = session.getTransport("smtp");
			transport.connect(host, userName, pwd);// 邮件服务器验证
			transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
			System.out.println("send ok...........................");
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * receive mail
	 * @throws IOException 
	 */
	public static List<Mail> receiveMail(String userName, String passWord) throws IOException {
		String host = "pop.163.com";
//		String userName = "wy245120020@163.com";
//		String passWord = "";
		List<Mail> rmailList = new ArrayList<>();

		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props);
		session.setDebug(true);
		try {
			System.out.println("receive...............................");
			Store store = session.getStore("pop3");
			store.connect(host, userName, passWord);// 验证
			Folder folder = store.getFolder("INBOX");// 取得收件文件夹
			folder.open(Folder.READ_WRITE);
			Message msg[] = folder.getMessages();
			System.out.println("邮件个数:" + msg.length);

			for (int i = 0; i < msg.length; i++) {
				Message message = msg[i];
				Address address[] = message.getFrom();
				StringBuffer from = new StringBuffer();
				/**
				 * 此for循环是我项目测试用的
				 */
				for (int j = 0; j < address.length; j++) {
					if (j > 0)
						from.append(";");
					from.append(address[j].toString());
				}
				
				Mail mail = new Mail();
				mail.setToAddress(userName);
				mail.setFromAddress(from.toString());
				mail.setSendTime(DateUtil.formatDate(message.getSentDate(), "yyyy-MM-dd hh:mm:ss"));
				mail.setContext(message.getContent().toString());
				
				System.out.println(message.getMessageNumber());
				System.out.println("来自：" + from.toString());
				System.out.println("大小：" + message.getSize());
				System.out.println("主题：" + message.getSubject());
				System.out.println("时间：：" + DateUtil.formatDate(message.getSentDate(), "yyyy-MM-dd hh:mm:ss"));
				System.out.println("内容：：" + message.getContent().toString());
				System.out.println("===================================================");
				rmailList.add(mail);
			}
			folder.close(true);// 设置关闭
			store.close();
			System.out.println("receive over............................");
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return rmailList;
	}

	/**
	 * delete mail
	 */
	public static void deleteMail() {
		String host = "pop3.sina.com";
		String userName = "xingui5624";
		String passWord = "******";

		Properties props = new Properties();
		// Properties props = System.getProperties();这种方法创建 Porperties 同上
		Session session = Session.getDefaultInstance(props);
		session.setDebug(true);
		try {
			System.out.println("begin delete ...........");
			Store store = session.getStore("pop3");
			store.connect(host, userName, passWord);// 验证邮箱
			Folder folder = store.getFolder("INBOX");
			folder.open(Folder.READ_WRITE);// 设置我读写方式打开
			int countOfAll = folder.getMessageCount();// 取得邮件个数
			int unReadCount = folder.getUnreadMessageCount();// 已读个数
			int newOfCount = folder.getNewMessageCount();// 未读个数
			System.out.println("总个数：" + countOfAll);
			System.out.println("已读个数：" + unReadCount);
			System.out.println("未读个数：" + newOfCount);
			for (int i = 1; i <= countOfAll; i++) {
				Message message = folder.getMessage(i);
				message.setFlag(Flags.Flag.DELETED, true);// 设置已删除状态为true
				if (message.isSet(Flags.Flag.DELETED))
					System.out.println("已经删除第" + i + "邮件。。。。。。。。。");
			}
			folder.close(true);
			store.close();
			System.out.println("delete ok.................................");
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}

	/**
	 * reply mail
	 */
	public static void replyMail() {
		// test
	}

}